var results_div = "search_results_area";
var info_div = "info_div";
var sort_01 ="last_name";
var direction_01 ="desc";

var progress_bar = function(wd,ht,txt,cl) {
	var throwaway = '<img src="/images/progress.gif" id="progress_bar" width="'+wd+'" height="'+ht+'" alt="'+txt+'" title="'+txt+'" align="absmiddle" style="padding:3px;"/>';	
	return throwaway;
};
var loading_bar = function(x,ele) {
	(x) ? $("#"+ele).html(progress_bar(16,16,'','blue')) : $("#"+ele).html('');
};

function clearStuff() {
	loading_bar(false,'state_loading');
	$('#state_query_string').val("");
	$('#info_div_state').html("");
}

function clear_cart() {
    $.ajax({
        type: 'GET',
        url: '/api/ajax_report_add.cfm?action=clear_cart&report_id=0',
        dataType: "json",
        success: function(json) {                
        },
        complete: function() {
           loadCart();
        },
        error: function(json) {                
        }                
   });
}

function closeReports() {
  $('#report_popup_new').css({display: 'none'});
  $('#report_popup').css({display: 'none'});
  $("#new_report_name").val('');
}

var showOldReports = function() {
  	function closer() {	  
      $('#report_popup').css({display: 'block'});
      $('#report_popup_new').css({display: 'none'});
      var popup = $("#add_old_00");
      var offset = popup.offset();
      $('#report_popup').css({left: offset.left+30, top: offset.top+(-50)});      
      $('#save_old_report').click(function(){
         $.ajax({
            type: 'GET',
            url: '/api/ajax_report_add.cfm?action=old&info='+$("#old_report").val(),
            dataType: "json",
            success: function(json) {                
            },
            complete: function() {
               loadCart();
               closeReports();
               load_old_reports();
            },
            error: function(json) {                
            }                
       });
               
      });
        $('#close_report_old_popup').click(function(){
        $('#report_popup').css({display: 'none'});				   
      });
  	}
  	return closer;
}

var showNewReports = function() {
	function closer() {	  
      $('#report_popup_new').css({display: 'block'});
      $('#report_popup').css({display: 'none'});
      var popup = $("#add_new_00");
      var offset = popup.offset();
      $('#report_popup_new').css({left: offset.left+30, top: offset.top+(-50)});      
      $('#close_report_new_popup').click(function(){
          $('#report_popup_new').css({display: 'none'});				   
      });
      $('#save_new_report').click(function(){
        $.ajax({
            type: 'GET',
            url: '/api/ajax_report_add.cfm?action=new&info='+$("#new_report_name").val(),
            dataType: "json",
            success: function(json) {                
            },
            complete: function() {
               loadCart();
               closeReports();
               load_old_reports();
            },
            error: function(json) {                
            }                
       });
                 
      });
	}
	return closer;
}

var addState = function() {
	var tmp_string =$("#state").val();
	if(tmp_string != 'not_selected'){
		//$('#info_div_state').innerfade({ animationtype: 'fade', speed: 650, timeout: 2000, type: 'sequence'});	
		var qstring = $('#state_query_string').val() + $('#state').val() +'_';
		$('#state_query_string').val(qstring);
		var dstring = '';
		dstring += $('#info_div_state').text() + $("#state").val() + " ";
		$('#info_div_state').html(dstring);	
	}
	loading_bar(false,'state_loading');
	
}

var load_old_reports = function() {
	$.ajax({
		type: 'GET',
		url: '/api/ajax_report_add.cfm?action=load_old_reports',		   
        dataType: "json",
        success: function(json) {
			var result_text = '';
			result_text += '<select id="old_report">';
			$.map(json.old_reports,function(n){
               result_text += '<option value="'+ n.report_id +'">'+ n.report_description +'</option>';
            });			
			result_text += '</select>';
			$('#old_report_selector').html(result_text);		
		},
		complete: function(json){ console.debug("complete"); },
        error: function(json){ console.debug("fail"); }
    });
}

function delete_cart(id) {
       $.ajax({
            type: 'GET',
            url: '/api/ajax_report_add.cfm?action=delete_poc&id='+id,
            dataType: "json",
            success: function(json) {
				$('#clear_cart2').html(''+progress_bar(16,16,'',''));
                loadCart();
            },
            error: function(json) {                
            }                
      }); 
}
//onmouseover="'+Tip('Some text', STICKY, true, FOLLOWSCROLL, true)+'"
var loadCart = function() {
   $.ajax({
            type: 'GET',
            url: '/api/ajax_report_add.cfm?action=display',
            dataType: "json",
            success: function(json) {
             
              var result_text = '';
              var pdf_list = '';
              $.map(json.report_poc, function(results_array) {
                 result_text += '<tr><td><a target="_blank" href="/edit.cfm?id=' + results_array.poc_id + '" style="font-size:11px;" >' +  results_array.first_name + ' ' +  results_array.last_name + '</a>&nbsp;<img src="/images/image_delete.gif" border="0" alt="Delete From Report" title="Delete From Report" align="absmiddle" style=" cursor:pointer;" id="delete_report_' +  results_array.poc_id  + '" /></td></tr>'; 
                 pdf_list += results_array.poc_id + ',';
                 
                  });
              $("#shopping_cart").html('<table width="100%" cellspacing="0" cellpadding="0" border="0" id="sc_rows">' + result_text + '</table>' );
                            
              $("img[id^='delete_report_']").bind("click", function(e){
                delete_cart(e.target.id.replace('delete_report_', ""));
              });
              $("#pdf_list").val('');
              $("#pdf_list").val(pdf_list);
			  $("#progress_bar").remove();
            },
            complete: function() {
                 $("#progress_bar").remove();
            },
            error: function(json) {                
            }                
      });
}

var page_load_results = function() {	
$("#"+results_div).html('<table id="" border="1" cellspacing="0" cellpadding="0" width="100%" class="datagrid"><thead><tr><th  width="2%"><input type="checkbox" id="select_all" name="select_all"  /></th><th><div id="sort_state">Location</div></th><th ><div id="sort_city">Jurisdiction</div></th><th  ><div id="sort_gov_type">Agency Type</div></th><th><div id="sort_gov_type_name">Agency Name</div></th><th ><div id="sort_address">Agency Physical Address</div></th><th ><div id="sort_last_name">Contact Last Name</div></th><th ><div id="sort_first_name">Contact First Name</div></th><th ><div id="sort_title">Contact Title</div></th><th ><div id="sort_email">Contact Email</div></th><th ><div >Contact Phone </div></th></tr></thead><tbody><tr><td colspan="11" id="loading_area" ><div align="center" class="Content_Margin">Loading Information<br />'+progress_bar(32,32,'','')+'</div></td></tr></table>');	

$.ajax({
		type: 'GET',
		url: "/api/ajax_poc_search.cfm?action=get_first"+
		"&search_term_1="+$('#poc_type').val()+
		"&search_term_2="+$('#gov_type').val()+
		"&search_term_3="+$('#discipline').val()+
		"&search_term_4="+$('#name').val()+
		"&search_term_5="+$('#company').val()+
		"&search_term_6="+$('#state_query_string').val()+
		"&search_term_7="+$('#five_star_area_category').val()+
		"&category="+$('#category').val()+
		"&start="+$('#tf_start').val()+
		"&end="+$('#tf_end').val()+
		"&lowest_term="+$('#lowest_term').val()+
		"&highest_term="+$('#highest_term').val()+
		"&count="+$('#count').val()+
		"&sort_column="+sort_01+
		"&sort_direction="+direction_01,		   
        dataType: "json",
        success: function(json) {
			
		},
		complete: function(json){  },
        error: function(json){  
			$("#"+results_div).html('<table id="" border="1" cellspacing="0" cellpadding="0" class="datagrid"><thead><tr><th  width="2%"><input type="checkbox" id="select_all" name="select_all"  /></th><th><div id="sort_state">Location</div></th><th ><div id="sort_city">Jurisdiction</div></th><th  ><div id="sort_gov_type">Agency Type</div></th><th><div id="sort_gov_type_name">Agency Name</div></th><th ><div id="sort_address">Agency Physical Address</div></th><th ><div id="sort_last_name">Contact Last Name</div></th><th ><div id="sort_first_name">Contact First Name</div></th><th ><div id="sort_title">Contact Title</div></th><th ><div id="sort_email">Contact Email</div></th><th ><div >Contact Phone </div></th></tr></thead><tbody><tr><td colspan="11" id="loading_area">No Search Results</td></tr></table>');
		}
    });
}

var searchPoc = function(clicked_action,sort_col,sort_dir) {		
	$('#'+results_div).html('<table id="" border="1" cellspacing="0" cellpadding="0" class="datagrid"><thead><tr><th  width="2%"><input type="checkbox" id="select_all" name="select_all"  /></th><th><div id="sort_state">Location</div></th><th ><div id="sort_city">Jurisdiction</div></th><th  ><div id="sort_gov_type">Agency Type</div></th><th><div id="sort_gov_type_name">Agency Name</div></th><th ><div id="sort_address">Agency Physical Address</div></th><th ><div id="sort_last_name">Contact Last Name</div></th><th ><div id="sort_first_name">Contact First Name</div></th><th ><div id="sort_title">Contact Title</div></th><th ><div id="sort_email">Contact Email</div></th><th ><div >Contact Phone </div></th></tr></thead><tbody><tr><td colspan="11" id="loading_area"><div align="center" class="Content_Margin">Loading Information<br />'+progress_bar(32,32,'','')+'</div></td></tr></table>');	

	$('#sort_').val( sort_col);
	$('#sort_direction').val(sort_dir);
	sort_01 = $('#sort_').val( );
	direction_01 = $('#sort_direction').val();
	
    var tmp = $('#sort_direction').val();
		if (tmp == "desc")
		{
			$('#sort_direction').val("asc") ;
		}
		else 
		{
			$('#sort_direction').val("desc");
		}

		$.ajax({
		type: 'GET',
		url: "/api/ajax_poc_search_results.cfm?action="+clicked_action+""+
		"&search_term_1="+$('#poc_type').val()+
		"&search_term_2="+$('#gov_type').val()+
		"&search_term_3="+$('#discipline').val()+
		"&search_term_4="+$('#name').val()+
		"&search_term_5="+$('#company').val()+
		"&search_term_6="+$('#state_query_string').val()+
		"&search_term_7="+$('#five_star_area_category').val()+
		"&category="+$('#category').val()+
		"&start="+$('#tf_start').val()+
		"&end="+$('#tf_end').val()+
		"&lowest_term="+$('#lowest_term').val()+
		"&highest_term="+$('#highest_term').val()+
		"&count="+$('#count').val()+
		"&sort_column="+$('#sort_').val()+
		"&sort_direction="+$('#sort_direction').val(),
        dataType: "json",
        success: function(json) {
		var json_data = [];
		var json_search_data = [];
		json_data = json.result;
		json_search_data = json.search_info;
		
		results_text = '';
		
		results_text += '<table id="" border="1" cellspacing="0" cellpadding="0" class="datagrid"><thead><tr><th  width="2%"><input type="checkbox" id="select_all" name="select_all" class="checkbox_results" /></th><th><div id="sort_state">Location</div></th><th ><div id="sort_city">Jurisdiction</div></th><th  ><div id="sort_gov_type">Agency Type</div></th><th><div id="sort_gov_type_name">Agency Name</div></th><th ><div id="sort_address">Agency Physical Address</div></th><th ><div id="sort_last_name">Contact Last Name</div></th><th ><div id="sort_first_name">Contact First Name</div></th><th ><div id="sort_title">Contact Title</div></th><th ><div id="sort_email">Contact Email</div></th><th ><div id="sort_phone">Contact Phone </div></th></tr></thead>';

        $.map(json_data,function(json_data){    
				results_text += '<tbody><tr><td align="center" valign="absmiddle"><input type="checkbox" class="checkbox_results" id="_filter_' +  json_data.poc_id + '" name="_filter_' +  json_data.poc_id + '" value="' +  json_data.poc_id + '"/></td><td>' +  json_data.column_state + '&nbsp;</td><td>' +  json_data.column_city + '&nbsp;</td><td>' +  json_data.column_gov_type + '&nbsp;</td><td>' +  json_data.column_company + '&nbsp;</td><td>' +  json_data.column_address + '&nbsp;</td><td><a target="_blank" href="/edit.cfm?id=' + json_data.poc_id + '" >' +  json_data.column_last_name + '</a></td><td><a target="_blank" href="/edit.cfm?id=' + json_data.poc_id + '">' +  json_data.column_first_name + '</a></td><td>' +  json_data.column_title + '&nbsp;</td><td align="ceneter"><a href="/email.cfm?type=poc&id='+json_data.poc_id+'"  target="blank" ><img id="" border="0" align="center" title="Email '+ json_data.column_email +'" alt="Email '+ json_data.column_email +'" src="/images/mail-forward.png"/></a>&nbsp;</td><td>' +  json_data.column_phone + '&nbsp;</td></tr></tbody>';
				
		
		});	
		
		results_text += '</td></tr>';
		results_text += '<tr><td class="s_nav" colspan="11" width="100%" style="border:none;" >'+
		'<table width="100%" class="search_nav"  style="border:none;"><tr><td align="left" width="40%"'+
		'  style="border:none;"><img src="/images/media-skip-backward.png" id="link_first" '+
		'align="absmiddle" alt="" class="img" alt="First" title="First" style="cursor:pointer;">&nbsp;<img src="/images/media-seek-backward.png" id="link_previous" align="absmiddle" class="img" alt="Previous" title="Previous" style="cursor:pointer;">&nbsp;&nbsp;&nbsp;<img src="/images/media-seek-forward.png" id="link_next" align="absmiddle" alt="" style="cursor:pointer;"class="img" alt="Next" title="Next">&nbsp;<img src="/images/media-skip-forward.png" id="link_last" align="absmiddle" alt="" class="img" alt="Last" title="Last" style="cursor:pointer;"> </td><td width="20%" align="center"  style="border:none;"><span class="" id="search_results_span">Results ' + json_search_data[0].lowest + '-' + json_search_data[0].highest + ' of ' + json_search_data[0].count + '</span></td><td align="right" width="40%"  style="border:none;"><div style="text-align:right;"><img src="/images/media-skip-backward.png" id="link_first2" align="absmiddle" class="img" alt="First" title="First" style="cursor:pointer;">&nbsp;<img src="/images/media-seek-backward.png" id="link_previous2" align="absmiddle" class="img" alt="Previous" title="Previous" style="cursor:pointer;">&nbsp;&nbsp;&nbsp;<img src="/images/media-seek-forward.png" id="link_next2" align="absmiddle"  class="img" alt="Next" title="Next" style="cursor:pointer;">&nbsp;<img src="/images/media-skip-forward.png" id="link_last2" align="absmiddle" class="img" alt="Last" title="Last" style="cursor:pointer;"></div></td></tr></table></td></tr>';
		
		results_text += '<tr><td class="s_nav" colspan="11" width="100%" style="border:none;" ><input type="button" value="Add to Shopping Cart" name="report_add_00" id="report_add_00" class="button"><span id="report_loading" class="loading"></span></td></tr></table>';
		$('#lowest_term').val(json_search_data[0].lowest);
		$('#highest_term').val(json_search_data[0].highest);
		$('#count').val(json_search_data[0].count) ;
		$("#"+results_div).html(results_text);
		$("#link_go").click(function() { searchPoc("get_first",sort_01,direction_01);return false; });
		$("#link_first").click(function() { searchPoc("get_first",sort_01,direction_01);return false; });
		$("#link_previous").click(function() { searchPoc("get_previous",sort_01,direction_01);return false; });
		$("#link_next").click(function() { searchPoc("get_next",sort_01,direction_01);return false; });
		$("#link_last").click(function() { searchPoc("get_last",sort_01,direction_01);return false; });
		$("#link_first2").click(function() { searchPoc("get_first",sort_01,direction_01);return false; });
		$("#link_previous2").click(function() { searchPoc("get_previous",sort_01,direction_01);return false; });
		$("#link_next2").click(function() { searchPoc("get_next",sort_01,direction_01);return false; });
		$("#link_last2").click(function() { searchPoc("get_last",sort_01,direction_01);return false; });	
		
		$("#sort_state").click(function() { searchPoc("get_first","state",$('#sort_direction').val()) });
		$("#sort_city").click(function() { searchPoc("get_first","city",$('#sort_direction').val()) });
		$("#sort_gov_type").click(function() { searchPoc("get_first","gov_type",$('#sort_direction').val()) });
		$("#sort_gov_type_name").click(function() { searchPoc("get_first","company",$('#sort_direction').val())});
		$("#sort_address").click(function() { searchPoc("get_first","address",$('#sort_direction').val())});
		$("#sort_last_name").click(function() { searchPoc("get_first","last_name",$('#sort_direction').val())});
		$("#sort_first_name").click(function() { searchPoc("get_first","first_name",$('#sort_direction').val())});
		$("#sort_title").click(function() { searchPoc("get_first","title",$('#sort_direction').val())});
		$('#select_all').click(function() { 
			var checked_status = this.checked;
			$("input[id^=_filter_]").each(function()
			{
				this.checked = checked_status;
			});							
		});
		$("#sort_email").click(function() { searchPoc("get_first","email",$('#sort_direction').val())});
		$("#report_add_00").click(function() { 
			$('#clear_cart2').html(''+progress_bar(16,16,'',''));
			var poc_list = '';
			
			$("input[id^=_filter_]").each(function()
			{				
				(this.checked) ? poc_list += this.id.split('_filter_').join("_") : poc_list += '';
			});
            
          $.ajax({
              type: 'GET',
              url: '/api/ajax_report_add.cfm?action=add_poc&id='+poc_list,
              dataType: "json",
              success: function(json) {
                loadCart();
				$("#progress_bar").remove();
              },
              error: function(json) {                
              }                
           });
       });
		},
		complete: function(){ 
			$("#progress_bar").remove();
		},
        error: function(json){  
			$("#"+results_div).html('<table id="" border="1" cellspacing="0" cellpadding="0" class="datagrid"><thead><tr><th  width="2%"><input type="checkbox" id="select_all" name="select_all"  />'+
			'</th><th><div id="sort_state">Location</div></th><th ><div id="sort_city">Jurisdiction</div></th><th  >'+
			'<div id="sort_gov_type">Agency Type</div></th><th><div id="sort_gov_type_name">Agency Name</div></th><th >'+
			'<div id="sort_address">Agency Physical Address</div></th><th ><div id="sort_last_name">Contact Last Name</div>'+
			'</th><th ><div id="sort_first_name">Contact First Name</div></th><th ><div id="sort_title">Contact Title</div>'+
			'</th><th ><div id="sort_email">Contact Email</div></th><th ><div >Contact Phone </div></th></tr></thead><tbody>'+
			'<tr><td colspan="11" id="loading_area">No Search Results</td></tr></table>');
		}
    });
}

$(function() {
	Functional.install();
	closeReports();
	loadCart();
	$("#link_go").click(function() {searchPoc("get_first",sort_01,direction_01)});
	$('#submit_state').click(function() { addState();return false;} );
	load_old_reports();
	page_load_results();
	clearStuff();
	$("#clear_state").click(function() { clearStuff(); return false; });
	$('#add_old_00').click(showOldReports());
	$('#add_new_00').click(showNewReports());
	$('#tf_start').datepicker({ dateFormat: 'mm/dd/yy' });
	$('#tf_end').datepicker({ dateFormat: 'mm/dd/yy' });
	$("#clear_cart").click(function() {
        clear_cart();
        return false;
	});
	$("#view_pdf").click(function() {
        window.open('/pdf_report.cfm?id=search&list='+$('#pdf_list').val(),'NIPD','');
	});
});